package com.im.partchat.http.apiManager;

import com.im.partchat.App;
import com.im.partchat.constant.Constatnt;
import com.im.partchat.http.interceptor.HeaderInterceptor;

import java.io.File;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;


/**
 * Created by ZHT on 2017/4/19.
 * 初始化OkHttp和Retrofit
 */

public class ApiManager {
    private static ApiManager instance = null;
    private static final long DEFAULT_TIME_OUT = 30;
    private static Retrofit retrofit;


    private ApiManager() {
    }
    public static ApiManager getInstance() {
        synchronized (ApiManager.class) {
            if (instance == null) {
                instance = new ApiManager();
                File cacheDir = new File(App.getApplication().getCacheDir(), "http");
                Cache cache = new Cache(cacheDir, 10 * 1024 * 1024);

                OkHttpClient.Builder builder = new OkHttpClient.Builder();
                builder.connectTimeout(DEFAULT_TIME_OUT, TimeUnit.SECONDS);
                builder.readTimeout(DEFAULT_TIME_OUT, TimeUnit.SECONDS);
                builder.writeTimeout(DEFAULT_TIME_OUT, TimeUnit.SECONDS);
                builder.addInterceptor(getLoggingInterceptor());
                builder.addInterceptor(new HeaderInterceptor());
                builder.cache(cache);
                OkHttpClient client = builder.build();
                Retrofit.Builder retrofitBuilder = new Retrofit.Builder();
                 retrofit = retrofitBuilder.baseUrl(Constatnt.BASE_URL)
                        .client(client)
                        .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                        .addConverterFactory(GsonConverterFactory.create())
                        .build();



            }
        }

        return instance;
    }

    public  <T> T  getApi(Class<T> cls) {
        return   retrofit.create(cls);
    }



    private static HttpLoggingInterceptor getLoggingInterceptor() {
        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);
        return logging;
    }
}
